package com.chenfan.mcn.event.subscriber;

import com.alibaba.fastjson.JSON;
import com.chenfan.common.vo.Response;
import com.chenfan.common.vo.ResponseCode;
import com.chenfan.mcn.clients.baseinfo.BaseInfoClient;
import com.chenfan.mcn.extension.log.FieldChangeOperateLog;
import com.chenfan.mcn.event.OperateLogEvent;
import com.chenfan.mcn.extension.log.FieldChangeDTO;
import com.chenfan.mcn.extension.log.FieldChangeUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Objects;

/**
 * 操作日志事件订阅者
 *
 * @author wulg
 * @date 2021-11-17
 **/
@Slf4j
@Component
public class OperateLogEventSubscriber implements EventSubscriber<OperateLogEvent> {

    @Autowired
    private BaseInfoClient baseInfoClient;

    /**
     * 操作日志订阅实现
     * @param event
     */
    @Override
    public void subscribe(OperateLogEvent event) {
        if(Objects.isNull(event.getBusinessId()) || Objects.isNull(event.getBusinessType())) {
            log.error("无效日志！事件报文：{}", JSON.toJSONString(event));
            return;
        }
        FieldChangeDTO<Object> fieldChangeDTO = new FieldChangeDTO<>(event.getOperationBy(), event.getOperationName(), event.getOperationTime());
        fieldChangeDTO.setTraceId(event.getTraceId());
        fieldChangeDTO.setActionName(event.getActionName());
        fieldChangeDTO.setRemark(event.getRemark());
        fieldChangeDTO.setBusinessId(event.getBusinessId());
        fieldChangeDTO.setBusinessType(event.getBusinessType());
        fieldChangeDTO.setOperationType(event.getOperationType());
        fieldChangeDTO.setBeforeValue(event.getBeforeValue());
        fieldChangeDTO.setAfterValue(event.getAfterValue());
        List<FieldChangeOperateLog> logList = FieldChangeUtil.contrast(fieldChangeDTO);
        if(CollectionUtils.isEmpty(logList)) {
            return;
        }
        Response response = baseInfoClient.insertLog(logList);
        if (ResponseCode.SUCCESS.getCode() != response.getCode()) {
            log.error("操作日志生成失败！报文：{}", JSON.toJSONString(logList));
        }
    }
}
